//
//  JYHomeWebViewController.m
//  ShareChatSell
//
//  Created by JiYi on 2018/8/8.
//  Copyright © 2018年 JiYi. All rights reserved.
//

#import "JYHomeWebViewController.h"
#import "UIViewController+JYURL.h"


@interface JYHomeWebViewController ()<UITabBarDelegate, UIWebViewDelegate>

@property (nonatomic, strong) UIWebView * webView;

@property (nonatomic, strong) UITabBar * tabBar;

@property (nonatomic, strong) UITabBarItem * tabBarItem1;
@property (nonatomic, strong) UITabBarItem * tabBarItem2;
@property (nonatomic, strong) UITabBarItem * tabBarItem3;
@property (nonatomic, strong) UITabBarItem * tabBarItem4;
@property (nonatomic, strong) UITabBarItem * tabBarItem5;

@property (nonatomic, strong) UIProgressView *loadingProgressView;
@property (assign, nonatomic) NSUInteger       loadCount;


@end

@implementation JYHomeWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //    self.automaticallyAdjustsScrollViewInsets = NO;
    //    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.tabBarController.tabBar.hidden = YES;
    
    //  隐藏顶部
    self.view.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:self.loadingProgressView];
    UIView * stBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    CGFloat stBarH = stBar.frame.size.height;
    [self.loadingProgressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(stBarH);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(@2);
    }];
    
    [self setupTabb];
    [self setupWebView];
    //进度条初始化
    //    [self progressLayerInitialize];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
    
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleDeviceOrientationDidChange:)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:nil
     ];
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIDeviceOrientationDidChangeNotification
                                                  object:nil];
}

- (void)handleDeviceOrientationDidChange:(UIInterfaceOrientation)interfaceOrientation
{
    //1.获取 当前设备 实例
    UIDevice *device = [UIDevice currentDevice] ;
    
    
    switch (device.orientation) {
        case UIDeviceOrientationFaceUp:
            NSLog(@"屏幕朝上平躺");
            
            break;
            
        case UIDeviceOrientationFaceDown:
            NSLog(@"屏幕朝下平躺");
            break;
            
            //系統無法判斷目前Device的方向，有可能是斜置
        case UIDeviceOrientationUnknown:
            NSLog(@"未知方向");
            [self normalWW];
            break;
            
        case UIDeviceOrientationLandscapeLeft:
            NSLog(@"屏幕向左横置");
            [self unNormalWW];
            break;
            
        case UIDeviceOrientationLandscapeRight:
            NSLog(@"屏幕向右橫置");
            [self unNormalWW];
            break;
            
        case UIDeviceOrientationPortrait:
            NSLog(@"屏幕直立");
            [self normalWW];
            break;
            
        case UIDeviceOrientationPortraitUpsideDown:
            NSLog(@"屏幕直立，上下顛倒");
            [self normalWW];
            break;
            
        default:
            NSLog(@"无法辨识");
            [self normalWW];
            break;
    }
}
- (void)normalWW {
    UIView * stBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    CGFloat stBarH = stBar.frame.size.height;
    [self.loadingProgressView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(stBarH);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(@2);
    }];
    
    [_webView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(stBarH);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.tabBar.mas_top);
    }];
}

- (void)unNormalWW {
    [self.loadingProgressView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(2);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(@2);
    }];
    
    [_webView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(2);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.tabBar.mas_top);
    }];
}

- (UIProgressView*)loadingProgressView {
    if (!_loadingProgressView) {
        _loadingProgressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, self.view.bounds.size.width, 2)];
        _loadingProgressView.progressTintColor = [UIColor redColor];
    }
    return _loadingProgressView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.view.backgroundColor = UIColor.whiteColor;
    self.navigationController.navigationBarHidden = YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
- (BOOL)shouldAutorotate {
    return YES;
}

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    
    return UIInterfaceOrientationPortrait;
}

- (void)progressLayerInitialize {
    
}

#pragma mark - 初始化tabbar
- (void)setupTabb {
    _tabBar = [[UITabBar alloc] init];
    [self.view addSubview:_tabBar];
    
    [_tabBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(@(50 + SafeAreaBottomHeight));
    }];
    
    
    NSArray * imageArr = @[@"首页", @"后退", @"前进", @"刷新", @"跳转"];
    NSArray * titleArr = @[@"首页", @"后退", @"前进", @"刷新", @"跳转"];
    NSInteger i = 0;
    NSMutableArray * items = [NSMutableArray array];
    for (NSString * imageName in imageArr) {
        UIImage * seletectImag = [[UIImage imageNamed:imageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UIImage * img = [UIImage imageNamed:imageName];
        
        UITabBarItem * item = [[UITabBarItem alloc] init];
        item.image = img;
        item.selectedImage = seletectImag;
        item.tag = i;
        item.title = titleArr[i];
        i++;
        
        [items addObject:item];
    }
    
    _tabBar.items = items;
    _tabBar.delegate = self;
    
    _tabBar.selectedItem = items.firstObject;
}

#pragma mark - 点击事件
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    switch (item.tag) {
        case 0:
            [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStrArr.firstObject]]];
            break;
        case 1:
            //  后退
            if (self.webView.canGoBack) {
                //如果有则返回
                [self.webView goBack];
                
            }
            break;
        case 2:
            //            [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStrArr[1]]]];
            //  后退
            if (self.webView.canGoForward) {
                //如果有则返回
                [self.webView goForward];
            }
            break;
        case 3:
            [self.webView reload];
            
            break;
        case 4:
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.urlStrArr[1]]];
            break;
        default:
            break;
    }
}

#pragma mark - 初始化
- (void)setupWebView {
    _webView = [[UIWebView alloc] init];
    _webView.backgroundColor = UIColor.whiteColor;
    _webView.delegate = self;
    [self.view addSubview:_webView];
    UIView * stBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    CGFloat stBarH = stBar.frame.size.height;
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(stBarH);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.tabBar.mas_top);
    }];
    
    [self.view insertSubview:_webView belowSubview:self.loadingProgressView];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
    self.loadCount ++;

}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    self.loadCount --;

    self.loadCount = 0;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    self.loadCount --;
    
    self.loadCount = 0;
}
#pragma mark 计算webView进度条
- (void)setLoadCount:(NSUInteger)loadCount
{
    _loadCount = loadCount;
    if (loadCount == 0)
    {
        self.loadingProgressView.hidden = YES;
        [self.loadingProgressView setProgress:0 animated:NO];
    }
    else
    {
        self.loadingProgressView.hidden = NO;
        CGFloat oldP = self.loadingProgressView.progress;
        CGFloat newP = (1.0 - oldP) / (loadCount + 1) + oldP;
        if (newP > 0.95)
        {
            newP = 0.95;
        }
        [self.loadingProgressView setProgress:newP animated:YES];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
